package com.boatAnchorAssistant.service.utils;

import lombok.extern.slf4j.Slf4j;
import nirvana.core.domains.vo.ApiResult;
import nirvana.core.exceptions.BizException;
import nirvana.core.utils.ids.IdGenerator;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.metrics.ApplicationStartup;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author anni.zhu
 * @author anni.zhu@king-v.com
 * Created in 2024/11/18 17:11
 */
@Slf4j
public class FileUtil {

    /**
     * 检查文件大小不能超过5MB
     */
    public static void checkFileSize(MultipartFile file) {
        if (file.getSize() > 5 * 1024 * 1024) {
            throw new BizException("文件大小不能超过5MB");
        }
    }

    /**
     * 上传
     * @param file
     * @param userId
     * @param title
     */
    public static String uploadFile(String fileName,MultipartFile file, Long userId, String title) {
        checkFileSize(file);

        if (file.isEmpty()) {
            throw new BizException("文件为空");
        }
        try {
            ApplicationHome home=new ApplicationHome(ApplicationStartup.class);
            System.out.println (home.getDir ());
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String property=home.toString();
            String url="/static/img/"+title+"/"+ fileName+suffix;
            String path = property+url;

            log.error("文件路径"+path);
            // 创建文件
            File dest = new File(path);
            // 判断文件父目录是否存在
            if (!dest.getParentFile().exists()) {
                log.error("文件父目录不存在");
                dest.getParentFile().mkdirs();
            }
            // 保存文件
            file.transferTo(dest);
            log.error("上传成功");
            return url;
        } catch (IllegalStateException e) {
            e.printStackTrace();
            throw new BizException("文件上传失败");
        } catch (IOException e) {
            e.printStackTrace();
            throw new BizException("文件上传失败");
        }
    }


}
